package org.usmile.algorithms.learn.graph.direction;

import org.usmile.algorithms.learn.graph.Graph;

public class CycleDetection {
    public boolean hasCycle(Graph graph) {
        boolean[] visited = new boolean[graph.getV()];
        boolean[] inOnPath = new boolean[graph.getV()];

        for (int v = 0; v < graph.getV(); v++) {
            if (!visited[v]) {
                if (dfs(graph, v, inOnPath, visited)) {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean dfs(Graph graph, int v, boolean[] isOnPath, boolean[] visited) {
        visited[v] = true;
        isOnPath[v] = true;
        for (int w : graph.adj(v)) {
            if (!visited[w]) {
                if (dfs(graph, w, isOnPath, visited)) {
                    return true;
                }
            } else {
                if (isOnPath[w]) {
                    return true;
                }
            }
        }
        isOnPath[v] = false;

        return false;
    }

    public static void main(String[] args) {
        Graph graph = new DirectionAdjSet(3);
        graph.addEdge(0, 1);
        graph.addEdge(0, 2);
        graph.addEdge(1, 2);
        System.out.println(new CycleDetection().hasCycle(graph));
    }
}
